﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Logic;
using Logic.ClarizenObjects;
using Logic.ClarizenSvc;

namespace ClarizenGadget.Controllers
{
    public class AttachmentsController : Controller
    {
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(string id, string type)
        {
            ViewBag.taskID = id;
            var elements = GetList(id, type);
            return View(elements);
        }

        public IEnumerable<Attachment> GetList(string id, string type)
        {
            var eq = new EntityQuery
            {
                Fields = BaseObject.GetFields(typeof(Attachment)),
                TypeName = type,
                Where = new Compare { LeftExpression = new FieldExpression { FieldName = "AttachedTo" }, Operator = Operator.Equal, RightExpression = new ConstantExpression { Value = new EntityId {TypeName="WorkItem", Value=id } } }
            };

            var elements = new QueryComponent().ExecuteQuery(eq);

            return elements.Select(e => BaseObject.Intitialize<Attachment>(e));
        }

        public ActionResult List(string task_id, string type)
        {
            ViewBag.TypeName = type;

            var notes = GetList(task_id, type);
            return View(notes);
        }
        
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Note note)
        {
            try
            {
                if (string.IsNullOrEmpty(note.ID.Value))
                {
                    note.ID = new QueryComponent().CreateEntity(note.ToGenericEntity());
                    note = BaseObject.Intitialize<Note>(new QueryComponent().RetrieveEntity(note.ID, BaseObject.GetFields(typeof(Note))));
                }
                else
                    new QueryComponent().UpdateEntity(note.ToGenericEntity());
                return Json(new GadgetResponse<Note> { Data = note, Status = GadgetResponseStatus.Success });
            }
            catch (Exception e)
            {
                return Json(new GadgetResponse<Boolean> { Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(String noteID)
        {
            try
            {
                new QueryComponent().DeleteEntity(new EntityId {TypeName="Note", Value = noteID });
                return Json(new GadgetResponse<Boolean> { Data = true, Status = GadgetResponseStatus.Success });
            }
            catch (Exception e)
            {
                return Json(new GadgetResponse<Boolean> { Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }
    }
}
